package geektime.spring.springbucks.waiterservice.service;

import geektime.spring.springbucks.waiterservice.model.Coffee;
import geektime.spring.springbucks.waiterservice.model.CoffeeOrder;
import geektime.spring.springbucks.waiterservice.model.OrderState;
import geektime.spring.springbucks.waiterservice.repository.CoffeeOrderRepository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.transaction.Transactional;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Transactional
@Slf4j
public class CoffeeOrderService {

    @Autowired
    private CoffeeOrderRepository orderRepository;

    public CoffeeOrder get(Long id) {
        CoffeeOrder one = orderRepository.getOne(id);
        log.info("one--> {}", one);
        return one;
    }

    public List<CoffeeOrder> getAll() {
        return orderRepository.findAll();
    }

    public CoffeeOrder createOrder(String customer,
                                   Coffee... coffees) {
        CoffeeOrder order = CoffeeOrder.builder().customer(customer).items(new ArrayList<>(Arrays.asList(coffees))).state(OrderState.INIT).build();

        CoffeeOrder saved = orderRepository.save(order);

        log.info("New Order : {}", saved);
        return saved;
    }

    public boolean updateState(CoffeeOrder order,
                               OrderState state) {
        if (state.compareTo(order.getState()) <= 0) {
            log.warn("Wrong state order:{},{}", state, order.getState());
            return false;
        }
        order.setState(state);
        orderRepository.save(order);
        log.info("Update Order:{}", order);
        return true;
    }

}
